// pages/list/list.ts
var { request } = getApp();
import XLSX from '../../utils/xlsx.mini.min.js'
function process(data :any){
	let workbook = XLSX.read(data, {
		type: "binary"
	});
	const sheetName = workbook.SheetNames[0]
	let sheet = workbook.Sheets[sheetName]
	const options = {
		raw: false // 如果不加raw:true的话日期会被读成数字，根据开发需求决定
	}
  const rawData = XLSX.utils.sheet_to_json(sheet, options);
  console.log(rawData,'rawData');
  // do something
  let  todoList = rawData.map(element => {
    let item = {} as any
    item.name = element.任务名称
    item.plan = element.任务方案
    item.finishTime = element.任务完成时间
    item.projectName = element.所属项目
    item.assigneeName = element.指派人员
    item.organizer = element.主办方
    item.level = element.任务等级=='正常'?0:1
    item.comment = element.领导批注
    item.progress = element.进展情况
    if(element.完成状态=='进行中'){
      item.status = 0
    }else if(element.完成状态=='已完成'){
      item.status = 1
    }else if(element.完成状态=='未完成'){
      item.status = 2
    }
    return item
  });
  console.log(todoList,'todoList');
  return todoList
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    active:'mine',
    allList:[] as any,
    list: [] as any,
    completeList: [] as any,
    incompleteList: [] as any,
    role :wx.getStorageSync('role'),
    progress:'',
    comment:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initTodoList()
  },
  onRefresh(){
    this.initTodoList()
  },
  initTodoList(assignee='') {
    request('/admin/task/list', {
      method: 'POST',
      data: {
        "current": "1",
        "size": "10000",
        "assignee": assignee,
      }
    }).then((res: any) => {
      if (res.data.code == 1) {
        let list = res.data.data.records.map(item=>{
          item.isOpen=false
          item.isUrgent = item.level==1
          return item
        })
        this.setData({
          list: list.filter((item: any) => item.status == 0),
          completeList: list.filter((item: any) => item.status == 1),
          incompleteList: list.filter((item: any) => item.status == 2),
          allList:list.map((item :any)=>{
            if(item.level==0){
              item.level ='正常'
            }else if(item.level==1){
              item.level ='紧急'
            }
            if(item.status== 0){
              item.status =  '进行中'
            }else if(item.status== 1){
              item.status =  '已完成'
            }else if(item.status== 2){
              item.status =  '未完成'
            }
            return item
          }),
        })
        console.log(this.data.list,'this.data.list');
      }
    })
  },
  handleSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  handleImport(){
    let that = this
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['.xls', '.xlsx'],
      success: res => {
        var tempFilePaths = res.tempFiles[0];
        console.log(tempFilePaths,'tempFilePaths');
        // 上传文件到服务器
        wx.uploadFile({
          url: 'http://120.26.209.113:8080/admin/task/importExcel', 
          header: {
            'token': wx.getStorageSync('token')
          },
          filePath: tempFilePaths.path, // 文件路径
          name: 'file', // 文件字段名，默认为file
          success: function(res) {
            // 上传成功，处理服务器返回的响应信息
            var data = res.data;
            console.log(res,'res');
            that.initTodoList()
          },
          fail: function(res) {
            // 上传失败，处理上传错误
            console.error(res,'err');
          }
        });
        // try {
        //   const path = res.tempFiles[0].path
        //   const fs = wx.getFileSystemManager()
        //   const data = fs.readFileSync(path, 'binary') // data为binary数据
        //   process(data)
        // } catch (e) {
        //   console.error(e)
        //   wx.showModal({
        //     title: '提示',
        //     content: "文件读取失败",
        //     showCancel: false
        //   })
        //   return
        // }
      }
    })    
  },
  handleExport(){
    console.log(XLSX,'handleExport');
    let sheet = [] //最终需要的数据
    let title = ["任务名称", "任务方案",'任务完成时间','所属项目','指派人员','主办方','任务等级','领导批注','进展情况','完成状态'] //表头
    sheet.push(title) //导入表头
    //循环表单数据
    console.log(this.data.allList,'this.data.allList');
    this.data.allList.forEach((item:any) => {
      // let json  = Object.values(item);
      // console.log(json,'json');
      let rowcontent = []
      rowcontent.push(item.name)
      rowcontent.push(item.plan)
      rowcontent.push(item.finishTime)
      rowcontent.push(item.projectName)
      rowcontent.push(item.assigneeName)
      rowcontent.push(item.organizer)
      rowcontent.push(item.level)
      rowcontent.push(item.comment)
      rowcontent.push(item.progress)
      rowcontent.push(item.status)
      sheet.push(rowcontent) //添加一行表单
    })
    console.log(sheet,'sheet');
    
    const worksheet = XLSX.utils.aoa_to_sheet(sheet);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "待办清单");
    const fileData = XLSX.write(workbook, {
      bookType: "xlsx",
      type: 'base64'
    });
    const filePath = `${wx.env.USER_DATA_PATH}/待办清单.xlsx` // 文件名对应表名，多个表的情况可以自己测试
    const fs = wx.getFileSystemManager()
    fs.writeFile({
      filePath: filePath,
      data: fileData,
      encoding: 'base64',
      success: res => {
        console.log(res)
        const sysInfo = wx.getSystemInfoSync()
        if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {
          wx.saveFileToDisk({
            filePath: filePath,
            success: console.log,
            fail: console.error
          })
        } else {
          wx.openDocument({
            filePath: filePath,
            showMenu: true, // 需要添加showMenu允许用户导出
            success: console.log,
            fail: console.error
          })
        }
      },
      fail: e => {
        console.error(e)
        if (e.errMsg.indexOf('locked')) {
          wx.showModal({
            title: '提示',
            content: '文档已打开，请先关闭',
          })
        }
      }
    })    
  },
  onChangeCard(e: any){
    console.log(e.detail.name,'onChangeCard');
    if(e.detail.name=='mine'){
      this.initTodoList(wx.getStorageSync('user'))
    }else{
      this.initTodoList()
    }
  },
  //展开结构分类菜单
  async handleDrawer(e: any) {
    let params = e.currentTarget.dataset
    console.log(params,'params');
    if (params.type == 0) {
      this.data.incompleteList.forEach(item=>{
        if(item.id == params.index){
          item.isOpen = !item.isOpen
        }
      })
      // this.data.incompleteList[params.index].isOpen = !this.data.incompleteList[params.index].isOpen
      this.setData({
        incompleteList: this.data.incompleteList,
      })
    } else {
      this.data.list.forEach(item=>{
        if(item.id == params.index){
          item.isOpen = !item.isOpen
        }
      })
      this.setData({
        list: this.data.list,
      })
    }
  },
  bindProgressInput(e: any){
    console.log(e.detail.value,'bindProgressBlur');
    this.setData({
      progress:e.detail.value
    })
  },
  bindCommentInput(e: any){
    console.log(e.detail.value,'bindCommentBlur');
    this.setData({
      comment:e.detail.value
    })
  },
  handleProgress(e: any){
    let param = e.currentTarget.dataset
    console.log(param,'handleProgress');
    request('/admin/task', {
      method:'POST',
      data:{
        id:param.id,
        progress:this.data.progress
      }
    }).then((res: any) => {
      if (res.data.code == 1) {
        console.log(res.data,'res.data');
      }
    })
  },
  handleComment(e: any){
    let param = e.currentTarget.dataset
    console.log(param,'handleComment');
    request('/admin/task', {
      method:'POST',
      data:{
        id:param.id,
        comment:this.data.comment
      }
    }).then((res: any) => {
      if (res.data.code == 1) {
        console.log(res.data,'res.data');
      }
    })
  },
  handleUnfinish(e: any){
    let param = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/unfinish/unfinish?id='+param.id,
    })
  },
  handleFinish(e: any){
    let param = e.currentTarget.dataset
    let that = this
    console.log(param,'handleFinish');
    wx.showModal({
      content: '确认完成当前待办任务吗？',
      success (res) {
        if (res.confirm) {
          request('/admin/task', {
            method:'POST',
            data:{
              id:param.id,
              status:1
            }
          }).then((res: any) => {
            if (res.data.code == 1) {
              console.log(res.data,'res.data');
              that.initTodoList()
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  handleEdit(e: any) {
    let param = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/edit/edit?addFlag=0&&todo='+JSON.stringify(param.todo),
    })
  },
  handleDel(e: any){
    let param = e.currentTarget.dataset
    let that = this
    wx.showModal({
      content: '确认删除当前待办任务吗？',
      success (res) {
        if (res.confirm) {
          request('/admin/task/delete', {
            method:'POST',
            data:{
              id:param.id
            }
          }).then((res: any) => {
            if (res.data.code == 1) {
              let list = res.data.data.records
              that.setData({
                assignList: list.filter((item: any) => 
                item.processStatus == 1),
              })
            }
          })
          that.initTodoList()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  handlePublish(){
    wx.navigateTo({
      url: '/pages/edit/edit?addFlag=1',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})